package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Department;
import cn.wolfcode.domain.Employee;
import cn.wolfcode.exception.LogicException;
import cn.wolfcode.mapper.EmployeeMapper;
import cn.wolfcode.qo.EmployeeQueryObject;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.util.UserContext;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@Service
public class EmployeeServiceImpl implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public void save(Employee employee, Long[] ids) {
        //对密码进行加密
        Md5Hash md5Hash = new Md5Hash(employee.getPassword(), employee.getName(),2);
        employee.setPassword(md5Hash.toString());
        //保存到数据库
        employeeMapper.insert(employee);
        //关联关系
        if (ids!=null&&ids.length>0) {
            for (Long roleId : ids) {
                employeeMapper.insertRelation(employee.getId(), roleId);
            }
        }
    }

    @Override
    public void delete(Long id) {
        employeeMapper.deleteByPrimaryKey(id);
        employeeMapper.deleteRelation(id);
    }

    @Override
    public void update(Employee employee, Long[] ids) {
        employeeMapper.updateByPrimaryKey(employee);

        employeeMapper.deleteRelation(employee.getId());
        //关联关系
        if (ids!=null&&ids.length>0) {
            for (Long roleId : ids) {
                employeeMapper.insertRelation(employee.getId(), roleId);
            }
        }

    }

    @Override
    public Employee get(Long id) {

        Employee employee = employeeMapper.selectByPrimaryKey(id);
        return employee;
    }

    @Override
    public List<Employee> listAll() {



        List<Employee> list = employeeMapper.selectAll();
        return list;
    }


    public PageInfo<Employee> query(EmployeeQueryObject qo) {
        /*int count = employeeMapper.selectForCount(qo);
        if (count == 0) {
            return new PageResult<>(qo.getCurrentPage(), qo.getPageSize(), count, Collections.emptyList());
        }
        //获取总页数
        int totalPage = count % qo.getPageSize()== 0
                ? count /qo.getPageSize() : count/ qo.getPageSize()+1;
        //判断当前页是否大于总页数,如果是,把总页数作为当前页查询分页结果集
        if (qo.getCurrentPage()>totalPage){
            qo.setCurrentPage(totalPage);
        }*/
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());

        List<Employee> employees = employeeMapper.selectForList(qo);
        return new PageInfo<>(employees);


    }

   /* @Override
    public Employee login(String username, String password) {
        *//*if (!(username!=null&&username.trim().length()>0)){
            throw new RuntimeException("用户名不为空");
        }
        if (!(password!=null&&password.trim().length()>0)){
            throw new RuntimeException("密码不为空");
        }*//*
        if (!StringUtils.hasText(username)){
            throw new LogicException("用户名不为空");
        }

        if (!StringUtils.hasText(password)){
            throw new LogicException("密码不为空");
        }
        Employee employee = employeeMapper.selectByUsernameAndPassword(username, password);
        if (employee == null){
            //通知调用者出现异常
            throw new LogicException("账号和密码不匹配");
        }
        if (employee.isStatus()!=true){
            throw new LogicException("账号已被禁用,请联系管理员");
        }
        return employee;
    }*/

    @Override
    public void updatePwd(String oldPassword,String newPassword) {
        Employee employee = UserContext.getCurrentUser();
        //从session中获取旧密码
        String oldPwd = employee.getPassword();
        if (!oldPwd.equals(oldPassword)){
            throw new RuntimeException("原密码错误");
        }

        //再将新密码设置到session中
        if (newPassword!=null){
            employee.setPassword(newPassword);
            employeeMapper.updateByPrimaryKey(employee);
        }else {
            throw new RuntimeException("新密码不能为空");
        }

    }

    @Override
    public void change(boolean status,Long id) {
        if (id != null){
            status = !status;
            employeeMapper.updateStatus(status, id);
        }

    }

    @Override
    public void batchDelete(Long[] ids) {
        if (ids!=null){
            employeeMapper.batchDelete(ids);

        }
    }

    @Override
    public Employee selectByName(String name) {
        return employeeMapper.selectByName(name);
    }

    @Override
    public Workbook exportXls() {
        //查询所有员工
        List<Employee> employees = employeeMapper.selectAll();

        //使用poi创建一个excel
        Workbook wb = new HSSFWorkbook();
        //创建excel中的一个表
        Sheet sheet = wb.createSheet("员工通讯录");

        //创建标题行数据,从0开始
        Row row = sheet.createRow(0);
        row.createCell(0).setCellValue("姓名");
        row.createCell(1).setCellValue("邮箱");
        row.createCell(2).setCellValue("年龄");
        for (int i = 0;i<employees.size();i++) {
            Employee employee = employees.get(i);
            row = sheet.createRow(i+1);
            //创建一个单元格,往单元格中写内容
            row.createCell(0).setCellValue(employee.getName());
            row.createCell(1).setCellValue(employee.getEmail());
            row.createCell(2).setCellValue(employee.getAge());
        }
        return wb;

    }

    @Override
    public void importXls(MultipartFile file) throws IOException {

        //读取上传的文件,并且封装为一个Workbook对象
        Workbook wb = new HSSFWorkbook(file.getInputStream());
        //读第0张sheet表
        Sheet sheet = wb.getSheetAt(0);
        //获取最后一行的索引
        int lastRowNum = sheet.getLastRowNum();
        //标题行不需要读
        for (int i = 1;i<=lastRowNum;i++){
            Row row = sheet.getRow(i);
            Employee employee = new Employee();
            employee.setName(row.getCell(0).getStringCellValue());
            employee.setEmail(row.getCell(1).getStringCellValue());
            employee.setAge(Integer.valueOf(row.getCell(2).getStringCellValue()));
            employee.setPassword("1");
            employeeMapper.insert(employee);

        }

    }

    @Override
    public List<Employee> selectByRoleSn(String[] sns) {
        return employeeMapper.selectByRoleSn(sns);
    }


}


